package com.adtech.common.widgets.text;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Build;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.SparseBooleanArray;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.adtech.common.utils.DisplayUtil;
import com.adtech.common.R;


/**
 * Descr:   自定义可收缩文本的显示控件
 * Author:  bozaixing.
 * Email:   654152983@qq.com.
 * Date:    2017/12/27.
 */

public class ExpandableTextView extends LinearLayout implements View.OnClickListener {

    // 默认最高行数
    private static final int MAX_COLLAPSED_LINES = 3;


    // 默认动画执行时间
    private static final int DEFAULT_ANIM_DURATION = 200;


    // 内容textview
    protected TextView mContentTxt;


    // 展开收起textview
    protected TextView mExpandCollapseTxt;


    // 是否有重新绘制
    private boolean mRelayout;


    // 默认收起
    private boolean mCollapsed = true;


    // 动画执行时间
    private int mAnimationDuration;


    // 是否正在执行动画
    private boolean mAnimating;


    // 设置内容最大行数，超过隐藏
    private int mMaxCollapsedLines;


    // 当前Linerlayout容器的高度
    private int mCollapsedHeight;


    // 内容TextView真实高度（含padding）
    private int mTextHeightWithMaxLines;


    // 内容MarginTopAndBottom的高度
    private int mMarginBetweenTxtAndBottom;


    // 内容文字字体的大小
    private int mContentTextColor;

    // 内容文字字体的大小
    private float mContentTextSize;


    // 收起展开文字字体的颜色
    private int mCollapseExpandTextColor;

    // 收起展开文字字体的大小
    private float mCollapseExpandTextSize;

    // 收起文字
    private String mTextCollapse;

    // 展开文字
    private String mTextExpand;

    // 收起展开位置，默认左边
    private int mGrarity;


    // Listview等列表情况下保存每个item的收起/展开状态
    private SparseBooleanArray mCollapsedStatus;

    // 列表Item的索引位置
    private int mPosition;


    // 展开收起状态回调
    private OnExpandStateChangeListener mListener;



    public ExpandableTextView(Context context) {
        this(context, null);
    }

    public ExpandableTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public ExpandableTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(attrs);
    }

    @Override
    public void setOrientation(int orientation) {
        // 固定为垂直方向上显示
        if (LinearLayout.HORIZONTAL == orientation) {
            throw new IllegalArgumentException("ExpandableTextView only supports Vertical Orientation.");
        }
        super.setOrientation(orientation);
    }
    /**
     * 初始化属性
     * @param attrs
     */
    private void init(AttributeSet attrs) {
        mCollapsedStatus=new SparseBooleanArray();

        TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.ExpandableTextView);
        mMaxCollapsedLines = typedArray.getInt(R.styleable.ExpandableTextView_maxCollapsedLines, MAX_COLLAPSED_LINES);
        mAnimationDuration = typedArray.getInt(R.styleable.ExpandableTextView_animDuration, DEFAULT_ANIM_DURATION);

        mTextCollapse = typedArray.getString(R.styleable.ExpandableTextView_textCollapse);
        mTextExpand = typedArray.getString(R.styleable.ExpandableTextView_textExpand);

        mContentTextColor = typedArray.getColor(R.styleable.ExpandableTextView_contentTextColor, ContextCompat.getColor(getContext(), R.color.black));
        mContentTextSize = typedArray.getDimension(R.styleable.ExpandableTextView_contentTextSize, DisplayUtil.sp2px(getContext(),12));

        mCollapseExpandTextColor = typedArray.getColor(R.styleable.ExpandableTextView_collapseExpandTextColor, ContextCompat.getColor(getContext(), R.color.black));
        mCollapseExpandTextSize = typedArray.getDimension(R.styleable.ExpandableTextView_collapseExpandTextSize, DisplayUtil.sp2px(getContext(),12));

        mGrarity = typedArray.getInt(R.styleable.ExpandableTextView_collapseExpandTextGrarity, Gravity.LEFT);

        typedArray.recycle();
        // enforces vertical orientation
        setOrientation(LinearLayout.VERTICAL);
        // default visibility is gone
        setVisibility(GONE);
    }

    /**
     * 渲染完成时初始化view
     */
    @SuppressLint("MissingSuperCall")
    @Override
    protected void onFinishInflate() {
        initwidgets();
    }

    /**
     * 初始化显示控件
     */
    private void initwidgets() {

        // 加载布局文件
        LayoutInflater inflater = (LayoutInflater) getContext()
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.layout_expand_collapse, this);

        // 显示内容的TextView
        mContentTxt = (TextView) findViewById(R.id.content_txt);
        mContentTxt.setOnClickListener(this);

        // 显示按钮的TextView
        mExpandCollapseTxt = (TextView) findViewById(R.id.expand_collapse_txt);
        setExpandCollapseText();
        mExpandCollapseTxt.setOnClickListener(this);

        mContentTxt.setTextColor(mContentTextColor);
        mContentTxt.getPaint().setTextSize(mContentTextSize);

        mExpandCollapseTxt.setTextColor(mCollapseExpandTextColor);
        mExpandCollapseTxt.getPaint().setTextSize(mCollapseExpandTextSize);

        //设置收起展开位置：左或者右
        LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
        layoutParams.gravity = mGrarity;
        mExpandCollapseTxt.setLayoutParams(layoutParams);
    }
    /**
     * 点击事件
     * @param view
     */
    @Override
    public void onClick(View view) {
        if (mExpandCollapseTxt.getVisibility() != View.VISIBLE) {
            return;
        }
        mCollapsed = !mCollapsed;
        //修改收起/展开文字
        setExpandCollapseText();
        //保存位置状态
        if (mCollapsedStatus != null) {
            mCollapsedStatus.put(mPosition, mCollapsed);
        }
        // 执行展开/收起动画
        mAnimating = true;
        ValueAnimator valueAnimator;
        if (mCollapsed) {
//            mTvContent.setMaxLines(mMaxCollapsedLines);
            valueAnimator = new ValueAnimator().ofInt(getHeight(), mCollapsedHeight);
        } else {
            valueAnimator = new ValueAnimator().ofInt(getHeight(), getHeight() +
                    mTextHeightWithMaxLines - mContentTxt.getHeight());
        }
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener(){
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                int animatedValue = (int) valueAnimator.getAnimatedValue();
                mContentTxt.setMaxHeight(animatedValue - mMarginBetweenTxtAndBottom);
                getLayoutParams().height = animatedValue;
                requestLayout();
            }
        });
        valueAnimator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animator) {

            }
            @Override
            public void onAnimationEnd(Animator animator) {
                // 动画结束后发送结束的信号
                /// clear the animation flag
                mAnimating = false;
                // notify the listener
                if (mListener != null) {
                    mListener.onExpandStateChanged(mContentTxt, !mCollapsed);
                }
            }
            @Override
            public void onAnimationCancel(Animator animator) {

            }
            @Override
            public void onAnimationRepeat(Animator animator) {

            }
        });
        valueAnimator.setDuration(mAnimationDuration);
        valueAnimator.start();
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        // 当动画还在执行状态时，拦截事件，不让child处理
        return mAnimating;
    }
    /**
     * 重新测量
     * @param widthMeasureSpec
     * @param heightMeasureSpec
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // If no change, measure and return
        if (!mRelayout || getVisibility() == View.GONE) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            return;
        }
        mRelayout = false;

        // Setup with optimistic case
        // i.e. Everything fits. No button needed
        mExpandCollapseTxt.setVisibility(View.GONE);
        mContentTxt.setMaxLines(Integer.MAX_VALUE);

        // Measure
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        //如果内容真实行数小于等于最大行数，不处理
        if (mContentTxt.getLineCount() <= mMaxCollapsedLines) {
            return;
        }
        // 获取内容tv真实高度（含padding）
        mTextHeightWithMaxLines = getRealTextViewHeight(mContentTxt);

        // 如果是收起状态，重新设置最大行数
        if (mCollapsed) {
            mContentTxt.setMaxLines(mMaxCollapsedLines);
        }
        mExpandCollapseTxt.setVisibility(View.VISIBLE);

        // Re-measure with new setup
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        if (mCollapsed) {
            // Gets the margin between the TextView's bottom and the ViewGroup's bottom
            mContentTxt.post(new Runnable() {
                @Override
                public void run() {
                    mMarginBetweenTxtAndBottom = getHeight() - mContentTxt.getHeight();
                }
            });
            // 保存这个容器的测量高度
            mCollapsedHeight = getMeasuredHeight();
        }
    }
    /**
     * 获取内容内容显示控件真实高度（含padding）
     * @param textView
     * @return
     */
    private static int getRealTextViewHeight( TextView textView) {
        int textHeight = textView.getLayout().getLineTop(textView.getLineCount());
        int padding = textView.getCompoundPaddingTop() + textView.getCompoundPaddingBottom();
        return textHeight + padding;
    }

    /**
     * 设置收起展开图标位置和文字
     */
    private void setExpandCollapseText(){
        mExpandCollapseTxt.setText(mCollapsed ? mTextExpand : mTextCollapse);
    }


    /*********暴露给外部调用方法***********/

    /**
     * 设置收起/展开监听
     * @param listener
     */
    public void setOnExpandStateChangeListener( OnExpandStateChangeListener listener) {
        mListener = listener;
    }

    /**
     * 设置内容
     * @param text
     */
    public void setText( CharSequence text) {
        mRelayout = true;
        mContentTxt.setText(text);
        setVisibility(TextUtils.isEmpty(text) ? View.GONE : View.VISIBLE);
    }

    /**
     * 设置内容，列表情况下，带有保存位置收起/展开状态
     * @param text
     * @param position
     */
    public void setText( CharSequence text,int position) {
        mPosition = position;
        //获取状态，如无，默认是true:收起
        mCollapsed = mCollapsedStatus.get(position, true);
        clearAnimation();


        //设置收起/展开文字
        setExpandCollapseText();

        setText(text);

        getLayoutParams().height = ViewGroup.LayoutParams.WRAP_CONTENT;

        requestLayout();
    }

    /**
     * 获取内容
     * @return
     */
    public CharSequence getText() {
        if (mContentTxt == null) {
            return "";
        }
        return mContentTxt.getText();
    }

    /**
     * 定义状态改变接口
     */
    public interface OnExpandStateChangeListener {
        /**
         * @param textView   - TextView being expanded/collapsed
         * @param isExpanded - true if the TextView has been expanded
         */
        void onExpandStateChanged(TextView textView, boolean isExpanded);
    }
}
